<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiApplet\ApiBaseException;
use App\Services\WxMp\WxMpListService;
use Closure;

/**
 * 微信小程序接口中间件
 * @package App\Http\Middleware
 */
class CheckApiWxMiniProgram
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //校验是否传入微信应用ID
        if (!$request->hasHeader('appid')){
            throw new ApiBaseException('请指定微信应用ID', ApiBaseException::INVALID_APPID);
        }
        $appid = $request->header('appid', '');
        $mpListData = (new WxMpListService())->getValidMpByAppid($appid);
        if (empty($mpListData) || $mpListData['type'] != WxMpListService::TYPE_APPLET){
            throw new ApiBaseException('无效的小程序应用ID', ApiBaseException::INVALID_APPID);
        }
        //校验是否传入用户token
        $curRouteName = \Route::currentRouteName();
        if (!in_array($curRouteName, ['api.applet.userbase.gettoken'])){
            if (!$request->hasHeader('token')){
                throw new ApiBaseException('请传入用户token', ApiBaseException::INVALID_TOKEN);
            }
            $token = $request->header('token', '');
            $userData = (new \App\Services\WxUser\WxUserService($appid))->getUserByToken($token);
            if (empty($userData)){
                throw new ApiBaseException('token无效,请重新获取', ApiBaseException::INVALID_TOKEN);
            }
        }

        return $next($request);
    }
}
